using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Helpers
{
    public static class VoteHelper
    {
        private static string CurrentIP
        {
            get
            {
                return HttpContext.Current.Request.UserHostAddress;
            }
        }

        public static string CastVote()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            long id;
            DAL.Quote quote = null;
            if (Helpers.QueryStringHelper.TryGetInt64("q", out id))
            {
                quote = DAL.Quotes.Item(id);
            }            

            if (quote != null && quote.ApprovalStatus == DAL.Quote.QuoteStatus.Approved)
            {
                if (!DAL.Votes.HasUserVoted(quote, CurrentIP))
                {
                    int vote;
                    if (Helpers.QueryStringHelper.TryGetInt32("vote", out vote))
                    {
                        if (vote >= 1 && vote <= 5)
                        {
                            DAL.Vote myVote = new DAL.Vote();
                            myVote.Quote = quote;
                            myVote.IPAddress = CurrentIP;
                            DAL.Votes.Add(myVote);

                            quote.TotalVotes += vote;
                            quote.NumberOfVoters += 1;
                            DAL.Quotes.Save(quote);

                            sb.AppendLine("<div>Thanks for voting :)</div>");
                        }
                    }
                }
                else
                {
                    sb.AppendLine("ZOMG! You've already voted on this.</div>");
                }

                sb.AppendLine("<div class=\"voteheader\">");
                if (quote.Rating != double.NaN)
                {
                    sb.Append("Average Rating: ").AppendLine(quote.Rating.ToString());
                }
                else
                {
                    sb.AppendLine("Average Rating: n/a");
                }
                sb.AppendFormat("<div class=\"small\">Rated {0} times.</div>", quote.NumberOfVoters).AppendLine();
                sb.AppendLine("</div>");
            }
            else
            {
                sb.AppendLine("Quote not found.");
            }

            return sb.ToString();
        }
    }
}